import VectorLayer from 'ol/layer/Vector';
import VectorSource from 'ol/source/Vector';
import { Stroke, Style } from 'ol/style';
import GeoJSON from 'ol/format/GeoJSON';

import { CanvasScalarControl } from "@/assets/plugins/scalar-ol";
import { Arrow } from "@/assets/plugins/windbarb-arrow";
import { Isoline } from "@/assets/plugins/isoline";

import { getWeatherByType, getWeatherConfig, getWeatherLines } from "@/api/plat/nc"
import { dateFormat } from "@/utils/date"

import * as ValueColors from "@/assets/plugins/value.js";


export default {
  data() {
    return {
      weatherType: "temp", // 当前气象显示类型
      weatherData: null, // 当前渲染气象的数据
      weatherTime: null, // 当前渲染气象的时间
      weatherLayer: null, // 常规气象的图层
      isoLineLayer: null, // 等值线的图层
      isoLineShow: true, // 是否开启等值线
      borderLayer: null, // 边框图层
      currentLayer: null, // 方向标的图层
      currentData: null, // 方向数据
      mapFirstLoadComplete: false, // 首次渲染标识
      coordinatePoint: [], // 单点气象的经纬度，刷新用
      config: {}, // 配置项
      timeAxisShow: false, // 时间轴的显示
      tipList: [],
    }
  },
  methods: {
    getWeatherObj(type) {
      const getHeader = (row) => {
        return {
          lo1: row.lons,
          lo2: row.lone,
          la1: row.late - row.dx,
          la2: row.lats - row.dx,
          nx: (row.lone - row.lons) / row.dx,
          ny: (row.late - row.lats) / row.dy,
          dx: row.dx,
          dy: row.dy,
        }
      }
      const getWindHeader = (row) => {
        const head = {
          lo1: row.lons, // 小
          lo2: row.lone, // 大
          la1: row.late - 0.5, // 大
          la2: row.lats - 0.5, // 小
          nx: (row.lone - row.lons) / row.dx,
          ny: (row.late - row.lats) / row.dy,
          dx: row.dx,
          dy: row.dy,
        }
        return head
      }
      // 填充的算法
      const fillData = (coor, data, header) => {
        // 进行数据填充，判断前后是否有数据
        const du1 = 0.3;
        const du2 = 0.6;
        const du3 = 1;
        let value = 0
        let x = coor[0];
        let index = coor[1]
        // 先向左
        const getfillData = (du) => {
          const interval = parseInt(du / header.dx);
          if (data[index][x - interval] > -90) {
            value = data[index][x - interval]
          } else {
            // 再向右
            if (data[index][x + interval] > -90) {
              value = data[index][x + interval]
            } else {
              // 再向上
              if (data[index - interval] && data[index - interval][x] > -90) {
                value = data[index - interval][x]
              } else {
                // 再向下
                if (data[index + interval] && data[index + interval][x] > 90) {
                  value = data[index + interval][x]
                }
              }
            }
          }
        }
        getfillData(du1);
        if (value <= 0) {
          getfillData(du2);
        }
        if (value <= 0) {
          getfillData(du3);
        }
        return value
      }
      // 太湖切割算法
      const getTHList = (header) => {
        const lons = [118, 120.75];
        const lats = [30.75, 32];
        const yMin = Math.floor((lons[0] - header.lo1) / header.dx);
        const yMax = Math.ceil((lons[1] - header.lo1) / header.dx);
        const xMin = Math.floor((header.la1 - lats[1]) / header.dy);
        const xMax = Math.ceil((header.la1 - lats[0]) / header.dy);
        return [[xMin, xMax], [yMin, yMax]]
      }
      const fnObject = {
        temp: { // 温度
          fn: getWeatherByType,
          isBorder: true,
          isSort: false, // 获取数据是否需要颠倒
          deal: (row) => {
            const header = getHeader(row)
            let list = [];
            for (let index = 0; index < header.ny; ++index) {
              list = list.concat(row.data[0][index].slice(0, header.nx))
            }
            return [{
              header,
              data: list
            }]
          },
          isoLine: true
        },
        sst: { // 海温
          fn: getWeatherByType,
          isBorder: true,
          isSort: true,
          deal: (row) => {
            const header = getHeader(row)
            let list = [];
            for (let index = 0; index < header.ny; ++index) {
              const column = []
              for (let x = 0; x < header.nx; ++x) {
                const item = row.data[0][index][x];
                if (item > -90) {
                  column.push(item)
                } else {
                  // 进行数据填充，判断前后是否有数据
                  column.push(fillData([x, index], row.data[0], header))
                }
                // column.push(item < -90 ? 0 : item)
              }
              list = column.concat(list)
            }
            // 先判断当前是否在太湖
            const lons = [118, 120.75];
            const lats = [30.75, 32];
            if (header.lo1 < lons[0] && header.lo2 > lons[1]) {
              if (header.la2 < lats[0] && header.la1 > lats[1]) {
                // 去掉太湖
                const thList = getTHList(header);
                for (let x = thList[0][0]; x <= thList[0][1]; ++x) {
                  for (let y = thList[1][0]; y < thList[1][1]; ++y) {
                    const index = x * header.nx + y
                    list[index] = 0
                  }
                }
              }
            }
            return [{
              header,
              data: list
            }]
          },
          isoLine: true,
        },
        shww: { // 海浪
          fn: getWeatherByType,
          isBorder: true,
          isSort: true,
          deal: (row) => {
            const header = getHeader(row)
            let list = [];
            for (let index = 0; index < header.ny; ++index) {
              const column = [];
              for (let x = 0; x < header.nx; ++x) {
                const item = row.data[0][index][x];
                if (item > -90) {
                  column.push(item)
                } else {
                  // 进行数据填充，判断前后是否有数据
                  column.push(fillData([x, index], row.data[0], header))
                }
              }
              list = column.concat(list)
            }
            // 处理浪向的数据
            let olist = [];
            for (let index = 0; index < header.ny; ++index) {
              const column = []
              for (let x = 0; x < header.nx; ++x) {
                const item = row.data[1][index][x];
                column.push(item)
              }
              olist = column.concat(olist)
            }
            this.currentData = [
              {
                header,
                data: olist,
              }
            ]
            return [{
              header,
              data: list
            }]
          },
          isoLine: true,
        },
        flow: { // 流
          fn: getWeatherByType,
          isSort: true,
          deal: (row) => {
            const header = getHeader(row)
            // 先拼装成标准的数据
            let list = [];
            for (let item of row.data) {
              let column = []
              for (let col of item) {
                column = col.slice(0, col.length - 1).concat(column)
              }
              list.push({
                header: header,
                data: column
              })
            }
            // 再去计算流速
            let speedCol = []
            const fillWindData = (index, header, list) => {
              // 首先计算出index目前的位置
              const x = parseInt(index / header.nx);
              const y = index % header.nx;
              const du1 = 0.3;
              const du2 = 0.6;
              const du3 = 1;
              let value1 = -99;
              let value2 = -99;
              // 先向左
              const getfillData = (du) => {
                const interval = parseInt(du / header.dx);
                const ii = x * header.nx + (y - interval);
                if (list[0].data[ii] > -90) {
                  value1 = list[0].data[ii]
                  value2 = list[1].data[ii]
                } else {
                  // 再向右
                  const ii = x * header.nx + (y + interval);
                  if (list[0].data[ii] > -90) {
                    value1 = list[0].data[ii]
                    value2 = list[1].data[ii]
                  } else {
                    // 再向上
                    const ii = (x - interval) * header.nx + y
                    if (list[0].data[ii] > -90) {
                      value1 = list[0].data[ii]
                      value2 = list[1].data[ii]
                    } else {
                      // 再向下
                      const ii = (x + interval) * header.nx + y
                      if (list[0].data[ii] > -90) {
                        value1 = list[0].data[ii]
                        value2 = list[1].data[ii]
                      }
                    }
                  }
                }
              }
              let speed = 0
              getfillData(du1);
              if (value1 === -99) {
                getfillData(du2);
              }
              if (value1 === -99) {
                getfillData(du3);
              }
              if (value1 === -99) {
                return speed
              } else {
                speed = Math.sqrt(value1 * value1 + value2 * value2)
                return speed;
              }
            }
            for (let index = 0; index < (header.nx * header.ny); ++index) {
              const value1 = list[0].data[index];
              const value2 = list[1].data[index];
              if (value1 < -90 || value2 < -90) {
                // 当数据为空的时候，需要就近补值      
                const val = fillWindData(index, header, list)
                speedCol.push(val)
              } else {
                const speed = Math.sqrt(value1 * value1 + value2 * value2);
                speedCol.push(speed)
              }
            }
            let speedList = [{
              header: header,
              data: speedCol
            }]
            this.currentData = list
            // 先判断当前是否在太湖
            const lons = [118, 120.75];
            const lats = [30.75, 32];
            if (header.lo1 < lons[0] && header.lo2 > lons[1]) {
              if (header.la2 < lats[0] && header.la1 > lats[1]) {
                // 去掉太湖
                const thList = getTHList(header);
                for (let x = thList[0][0]; x <= thList[0][1]; ++x) {
                  for (let y = thList[1][0]; y < thList[1][1]; ++y) {
                    const index = x * header.nx + y
                    speedList[0].data[index] = 0
                  }
                }
              }
            }
            return speedList
          },
          isoLine: true,
        },
        wind: { // 风
          fn: getWeatherByType,
          isSort: true,
          deal: (row) => {
            let list = [];
            const header = getWindHeader(row)
            for (let item of row.data) {
              let column = [];
              for (let index = 0; index < header.ny; ++index) {
                // column = column.concat(item[index].slice(0, header.nx))
                column = (item[index].slice(0, header.nx)).concat(column)
              }
              list.push({
                header: header,
                data: column
              })
            }
            return list
          }
        },
        salt: { // 盐度
          fn: getWeatherByType,
          isBorder: true,
          isSort: true,
          // level: 1,
          deal: (row) => {
            const header = getHeader(row)
            let list = [];
            for (let index = 0; index < header.ny; ++index) {
              const column = []
              for (let x = 0; x < header.nx; ++x) {
                const item = row.data[0][index][x];
                if (item > -90) {
                  column.push(item)
                } else {
                  // 进行数据填充，判断前后是否有数据
                  if (item > -90) {
                    column.push(item)
                  } else {
                    // 进行数据填充，判断前后是否有数据
                    column.push(fillData([x, index], row.data[0], header))
                  }
                }
                // column.push(item < -90 ? 0 : item)
              }
              list = column.concat(list)
            }
            // 先判断当前是否在太湖
            const lons = [118, 120.75];
            const lats = [30.75, 32];
            if (header.lo1 < lons[0] && header.lo2 > lons[1]) {
              if (header.la2 < lats[0] && header.la1 > lats[1]) {
                // 去掉太湖
                const thList = getTHList(header);
                for (let x = thList[0][0]; x <= thList[0][1]; ++x) {
                  for (let y = thList[1][0]; y < thList[1][1]; ++y) {
                    const index = x * header.nx + y
                    list[index] = 0
                  }
                }
              }
            }
            return [{
              header,
              data: list
            }]
          },
          isoLine: true,
        },
      }
      return fnObject[type]
    },
    weatherMounted() {
      this.getWeatherData()
    },
    /**
     * 获取不同气象元素的数据
     * @param {*} type create: 新建图层 update: 更新图层
     * @param {*} date 时间，默认为当前时间
     */
    getWeatherData(type = "create", date = dateFormat(new Date(), "yyyy-MM-dd hh:mm:ss")) {
      let params = {
        type: this.weatherType,
        time: date,
      }
      const weatherObj = this.getWeatherObj(this.weatherType)
      if (weatherObj.level) {
        params.level = weatherObj.level
      }
      weatherObj.fn(params).then(({ data }) => {
        const weatherData = weatherObj.deal(data);
        this.weatherData = [...weatherData]
        if (type === "create") {
          this.createWeather()
        } else {
          this.updateWeather()
        }
        // 获取等值线
        if (weatherObj.isoLine && this.isoLineShow) {
          // 先清空等值线，在绘制
          if (this.isoLineLayer) {
            // 删除等值线的layers
            this.map.removeLayer(this.isoLineLayer)
            // 删除所有tips
            this.clearIsoLineTips()
          }
          let params = {
            type: this.weatherType + '',
            time: date
          }
          if (weatherObj.level) {
            params.level = weatherObj.level
          }
          getWeatherLines(params).then(({ data }) => {
            // this.isoLineDrawFn(data)
            // 因为数据请求慢，添加type来判断渲染的时候是否还是当前的type
            this.isoPolygonDrawFn(data, params.type)
          })
        }
        // 添加周围的边框
        // const header = weatherData[0].header;
        // this.drawBorder(header, weatherObj.isBorder)
        // 移动到中心点
        // const lon = (header.lo2 + header.lo1) / 2;
        // const lat = (header.la1 + header.la2) / 2;
        // this.UtilMethods.moveToCenterByLonAndLat([lon, lat], this.map)
      })
    },
    createWeather() {
      this[`${this.weatherType}DrawFn`]().create()
      this.$nextTick(() => {
        this.updateWeatherLayers("show");
      })
    },
    updateWeather() {
      CanvasScalarControl.update()
      this[`${this.weatherType}DrawFn`]().create()
      this.updateWeatherLayers("show");
    },
    // 更新气象图层
    updateWeatherLayers(operation) {
      if (this.mapFirstLoadComplete) {
        if (operation == "show") {
          this.weatherLayer.update();
          if (this.currentLayer) {
            this.currentLayer.update()
          }
        } else if (operation == "clear") {
          if (this.weatherLayer) {
            this.weatherLayer.clear();
          }
          if (this.currentLayer) {
            this.currentLayer.clear()
          }
        }
      }
    },
    // 温度的方法集合
    tempDrawFn() {
      return {
        create: () => {
          this.changeLayerIndex(this.weatherType)
          this.weatherLayer = (() => {
            return {
              update: () => {
                CanvasScalarControl.show();
                if (this.weatherData) {
                  CanvasScalarControl.draw(this.map, this.weatherData, "temp");
                }
              },
              clear: () => { }
            };
          })();
        },
        show: () => {
          this.weatherLayer.update();
        },
        clear: () => {
          CanvasScalarControl.clear(this.map);
          this.weatherLayer = null;
          this.weatherData = null;
          if (this.isoLineLayer) {
            // 删除等值线的layers
            this.map.removeLayer(this.isoLineLayer)
            // 删除所有tips
            this.clearIsoLineTips()
          }
        }
      }
    },
    // 风力的方法集合
    windDrawFn() {
      return {
        create: () => {
          this.changeLayerIndex(this.weatherType)
          this.weatherLayer = (() => {
            let arrow = new Arrow({ canvas: this.$refs.arrowCanvas, map: this.map });
            let productType = "wind";
            let lastestData = this.weatherData;

            function draw(data, productType) {
              arrow.draw({ srcData: data, productType: productType });
            }

            const update = () => {
              clear();
              draw(lastestData, productType);
            }

            function clear() {
              arrow && arrow.clear();
            }

            return {
              update: update,
              clear: clear,
            };
          })();
        },
        show: () => {
          this.weatherLayer.update();
        },
        clear: () => {
          this.weatherLayer.clear();
          this.weatherLayer = null;
          this.weatherData = null;
        }
      }
    },
    // 气压的方法集合
    mslDrawFn() {
      return {
        create: () => {
          this.weatherLayer = (() => {
            return {
              update: () => {
                CanvasScalarControl.show();
                if (this.weatherData) {
                  CanvasScalarControl.draw(this.map, this.weatherData, "msl");
                }
              },
              clear: () => { }
            };
          })();
        },
        show: () => {
          this.weatherLayer.update();
        },
        clear: () => {
          CanvasScalarControl.clear(this.map);
          this.weatherLayer = null;
          this.weatherData = null;
          if (this.isoLineLayer) {
            // 删除等值线的layers
            this.map.removeLayer(this.isoLineLayer)
            // 删除所有tips
            this.clearIsoLineTips()
          }
        }
      }
    },
    // 海温的方法集合
    sstDrawFn() {
      return {
        create: () => {
          this.changeLayerIndex(this.weatherType)
          this.weatherLayer = (() => {
            return {
              update: () => {
                CanvasScalarControl.show();
                if (this.weatherData) {
                  CanvasScalarControl.draw(this.map, this.weatherData, "sst");
                }
              },
              clear: () => { }
            };
          })();
        },
        show: () => {
          this.weatherLayer.update();
        },
        clear: () => {
          CanvasScalarControl.clear(this.map);
          this.weatherLayer = null;
          this.weatherData = null;
          if (this.isoLineLayer) {
            // 删除等值线的layers
            this.map.removeLayer(this.isoLineLayer)
            // 删除所有tips
            this.clearIsoLineTips()
          }
        }
      }
    },
    // 海浪的方法集合
    shwwDrawFn() {
      return {
        create: () => {
          this.changeLayerIndex(this.weatherType)
          // this.isoLineFn()
          // this.waveCurrentDrawFn().create()
          this.weatherLayer = (() => {
            return {
              update: () => {
                CanvasScalarControl.show();
                if (this.weatherData) {
                  CanvasScalarControl.draw(this.map, this.weatherData, "oceanWave");
                }
              },
              clear: () => {
                // this.isoLineLayer.clear();
              }
            };
          })();
        },
        show: () => {
          this.weatherLayer.update();
          // this.waveCurrentDrawFn().show();
          // 等值线
          // this.isoLineLayer.update()
        },
        clear: () => {
          CanvasScalarControl.clear(this.map);
          this.weatherLayer = null;
          this.weatherData = null;
          // this.waveCurrentDrawFn().clear()
          if (this.isoLineLayer) {
            // 删除等值线的layers
            this.map.removeLayer(this.isoLineLayer)
            // 删除所有tips
            this.clearIsoLineTips()
          }
        }
      }
    },
    // 盐度
    saltDrawFn() {
      return {
        create: () => {
          this.changeLayerIndex(this.weatherType)
          this.weatherLayer = (() => {
            return {
              update: () => {
                CanvasScalarControl.show();
                if (this.weatherData) {
                  CanvasScalarControl.draw(this.map, this.weatherData, "salt");
                }
              },
              clear: () => { }
            };
          })();
        },
        show: () => {
          this.weatherLayer.update();
        },
        clear: () => {
          CanvasScalarControl.clear(this.map);
          this.weatherLayer = null;
          this.weatherData = null;
          if (this.isoLineLayer) {
            // 删除等值线的layers
            this.map.removeLayer(this.isoLineLayer)
            // 删除所有tips
            this.clearIsoLineTips()
          }
        }
      }
    },
    // 流速的方法集合
    flowDrawFn() {
      return {
        create: () => {
          this.changeLayerIndex(this.weatherType)
          // this.oceanCurrentDrawFn().create()
          this.weatherLayer = (() => {
            return {
              update: () => {
                CanvasScalarControl.show();
                if (this.weatherData) {
                  CanvasScalarControl.draw(this.map, this.weatherData, "oceanCurrent");
                }
              },
              clear: () => { }
            };
          })();
        },
        show: () => {
          this.weatherLayer.update();
          // this.oceanCurrentDrawFn().show();
        },
        clear: () => {
          CanvasScalarControl.clear(this.map);
          this.weatherLayer = null;
          this.weatherData = null;
          // this.oceanCurrentDrawFn().clear()
          if (this.isoLineLayer) {
            // 删除等值线的layers
            this.map.removeLayer(this.isoLineLayer)
            // 删除所有tips
            this.clearIsoLineTips()
          }
        }
      }
    },
    // 等值线
    isoLineFn() {
      this.isoLineLayer = (() => {
        let isoline = null;
        let isolineCanvas = this.$refs.isolineCanvas;
        return {
          update: () => {
            const drawIsoline = (isolineJSON, productType) => {
              if (!isoline) {
                isoline = new Isoline({ canvas: isolineCanvas, map: this.map });
              }
              isoline.draw({ srcData: isolineJSON, productType: productType });
            }
            if (this.lineData) {
              drawIsoline(this.lineData);
            } else {
              isoline && isoline.clear();
            }
          },
          clear: () => {
            isoline && isoline.clear();
          },
        };
      })()
    },
    isoPolygonDrawFn(data, type) {
      if (type !== this.weatherType) return
      let polygon = JSON.parse(data)
      polygon.features = polygon.features.filter(m => m.properties.value !== 90)
      const { source, tipList } = this.DrawMethods.drawIsoPolygonFn(polygon, this.weatherType)
      // 先绘制等值线
      let layerTmp = this.map.getLayers().getArray().find(m => m.get("name") === "IsoLine")
      const line = ValueColors.lineColor[this.weatherType]
      if (!layerTmp) {
        this.isoLineLayer = new VectorLayer({
          source: new VectorSource({
            features: [],
          }),
          zIndex: 220,
          name: "IsoLine",
          style: [new Style({
            stroke: new Stroke({
              color: `rgb(${line})`,
              width: 1.5,
              lineJoin: 'round'  // 圆滑连接线
            })
          })]
        });
        this.map.addLayer(this.isoLineLayer)
      }
      this.isoLineLayer.setSource(source)
      // 再绘制tip
      this.tipList = tipList
      for (let item of this.tipList) {
        this.map.addOverlay(item.dom);
        item.dom.setPosition(this.UtilMethods.transformLonlatToNow(item.coor));
      }
    },
    isoLineDrawFn(data) {
      let polygon = JSON.parse(data)
      polygon = {
        type: "FeatureCollection",
        features: polygon.map(m => {
          return {
            "type": "Feature",
            "geometry": {
              "type": "LineString",
              "coordinates": m.PointList.map(m => [m.X, m.Y])
            },
            "properties": {
              value: m.value
            }
          }
        })
      }
      const { source, tipList } = this.DrawMethods.drawIsoLineFn(polygon, this.weatherType)
      // 先绘制等值线
      let layerTmp = this.map.getLayers().getArray().find(m => m.get("name") === "IsoLine")
      const line = ValueColors.lineColor[this.weatherType]
      if (!layerTmp) {
        this.isoLineLayer = new VectorLayer({
          source: new VectorSource({
            features: [],
          }),
          zIndex: 220,
          name: "IsoLine",
          style: [new Style({
            stroke: new Stroke({
              color: `rgb(${line})`,
              width: 1.5,
              lineJoin: 'round'  // 圆滑连接线
            })
          })]
        });
        this.map.addLayer(this.isoLineLayer)
      }
      this.isoLineLayer.setSource(source)
      // 再绘制tip
      this.tipList = tipList
      for (let item of this.tipList) {
        this.map.addOverlay(item.dom);
        item.dom.setPosition(this.UtilMethods.transformLonlatToNow(item.coor));
      }
    },
    // 清空等值线tips
    clearIsoLineTips() {
      var Drawom = document.getElementsByClassName("isoLine-tip");
      for (let i = Drawom.length - 1; i >= 0; --i) {
        if (Drawom[i] != null) Drawom[i].parentNode.removeChild(Drawom[i]);
      }
    },
    // 绘制气象边框
    drawBorder(header, isBorder) {
      const lo1 = header.lo1
      const lo2 = header.lo2
      const la1 = header.la1
      const la2 = header.la2
      const borderList = [
        this.UtilMethods.transformLonlatToNow([lo1, la1]),
        this.UtilMethods.transformLonlatToNow([lo1, la2 + header.dy]),
        this.UtilMethods.transformLonlatToNow([lo2 - header.dx, la2 + header.dy]),
        this.UtilMethods.transformLonlatToNow([lo2 - header.dx, la1]),
        this.UtilMethods.transformLonlatToNow([lo1, la1]),
      ]
      var source = new VectorSource({
        features: (new GeoJSON()).readFeatures({
          type: 'FeatureCollection',
          features: [
            {
              coordinates: [borderList],
              type: "Polygon"
            }
          ]
        })
      });
      this.clearBorder()
      if (isBorder) {
        this.borderLayer = new VectorLayer({
          source: source,
          zIndex: 9999,
          name: "borderLayer",
          style: [new Style({
            stroke: new Stroke({
              color: "#BBDAEF",
              width: 2,
              lineJoin: 'round'  // 圆滑连接线
            })
          })]
        });
        this.map.addLayer(this.borderLayer)
      }
    },
    clearBorder() {
      let layerTmp = this.map.getLayers().getArray().find(m => m.get("name") === "borderLayer")
      if (layerTmp) {
        this.map.removeLayer(layerTmp)
        this.borderLayer = null
      }
    },
    // 方向标 - 需uv计算
    oceanCurrentDrawFn() {
      return {
        create: () => {
          this.currentLayer = (() => {
            let arrow = new Arrow({ canvas: this.$refs.arrowCanvas, map: this.map });
            let productType = "oceanCurrent";
            let lastestData = this.currentData;

            function draw(data, productType) {
              arrow.draw({ srcData: data, productType: productType });
            }

            const update = () => {
              clear();
              draw(lastestData, productType);
            }

            function clear() {
              arrow && arrow.clear();
            }

            return {
              update: update,
              clear: clear,
            };
          })();
        },
        show: () => {
          this.currentLayer.update();
        },
        clear: () => {
          this.currentLayer.clear();
          this.currentLayer = null;
          this.currentData = null;
        }
      }
    },
    // 方向标 - 有直接的值
    waveCurrentDrawFn() {
      return {
        create: () => {
          this.currentLayer = (() => {
            let arrow = new Arrow({ canvas: this.$refs.arrowCanvas, map: this.map });
            let productType = "wave";
            let lastestData = this.currentData;

            function draw(data, productType) {
              arrow.draw({ srcData: data, productType: productType });
            }

            const update = () => {
              clear();
              draw(lastestData, productType);
            }

            function clear() {
              arrow && arrow.clear();
            }

            return {
              update: update,
              clear: clear,
            };
          })();
        },
        show: () => {
          this.currentLayer.update();
        },
        clear: () => {
          this.currentLayer.clear();
          this.currentLayer = null;
          this.currentData = null;
        }
      }
    },
    // 单点气象获取并渲染
    getWeatherByPoint(lonAndLat) {
      const weatherObj = this.getWeatherObj(this.weatherType)
      this.coordinatePoint = lonAndLat
      let params = {
        type: this.weatherType,
        lon: lonAndLat[0],
        lat: lonAndLat[1],
        time: this.weatherTime || dateFormat(new Date(), "yyyy-MM-dd hh:mm:ss"),
        isSort: weatherObj.isSort,
      }
      // if (this.weatherType === "salt") {
      //   params.level = 1
      // }
      this.TipMethods.drawOneWeatherInfo(this.map, params, this.openWeatherDetail)
      // 判断下曲线图是否显示中，现实中要刷新里面的数据
      const isDetail = this.$refs.WeatherDetail;
      if (isDetail) {
        if (isDetail.domHeight > 0) {
          this.openWeatherDetail(this.UtilMethods.transformLonlatToNow(lonAndLat))
        }
      }
    },
    // 根据时间进行数据的获取与渲染
    weatherTimeChange(time) {
      setTimeout(() => {
        this.weatherTime = time
        this.getWeatherData("update", time)
        // 判断单点框是否存在，存在的话，重新请求数据并刷新
        const weatherObj = this.getWeatherObj(this.weatherType)
        this.TipMethods.updateDrawWeatherInfo({
          type: this.weatherType,
          lon: this.coordinatePoint[0],
          lat: this.coordinatePoint[1],
          time: this.weatherTime || dateFormat(new Date(), "yyyy-MM-dd hh:mm:ss"),
          isSort: weatherObj.isSort,
        })
      }, 500);
    },
    // 清空操作
    clearWeather() { },
    // 打开单点气象详情
    openWeatherDetail(coordinate) {
      const coor = this.UtilMethods.transformNowToLonlat(coordinate)
      this.$refs.WeatherDetail.handleOpen(this.weatherType, coor, this.config)
    },
    // 配置项
    getWeatherConfig() {
      getWeatherConfig().then(({ data }) => {
        this.config = data;
        this.timeAxisShow = true
        // this.$refs.setting.timeForm = { ...this.config }
      })
    },
    // 更新配置项
    updateTimeAxis(data) {
      this.config = data;
      this.timeAxisShow = false
      this.$nextTick(() => {
        this.timeAxisShow = true
        this.weatherTimeChange(dateFormat(new Date()))
      })
    },
    // 切换图层
    changeLayerIndex(type) {
      const layer = this.map.getLayers().getArray().find(m => m.get("name") === "Main")
      if (type === "temp" || type === "wind") {
        layer.setZIndex(200)
      } else {
        layer.setZIndex(225)
      }
    }
  },
  mounted() {
    // 初始化获取气象config
    this.getWeatherConfig()
    setTimeout(() => {
      this.mapFirstLoadComplete = true
      // this.weatherMounted()
    }, 100);
  },
  watch: {
    weatherType(val, oldVal) {
      this.clearBorder()
      this[`${oldVal}DrawFn`]().clear()
      this.getWeatherData("create", this.weatherTime || dateFormat(new Date(), "yyyy-MM-dd hh:mm:ss"))
      // 将单点元素查询框关闭
      this.UtilMethods.removeDomById("oneMeteoInfoId")
      // TODO: 直接将现在的图层全部删除
      // 清空等值线
      if (this.isoLineLayer) {
        // 删除等值线的layers
        this.map.removeLayer(this.isoLineLayer)
        // 删除所有tips
        this.clearIsoLineTips()
      }
    }
  }
}